//
// Created by sagnitude on 12/30/2015.
//

#include "Logic.h"

String Logic::ListAd(String endUserSn, String triggerType, String appToken, String jsonBeacons) {

    redisReply * reply;

    std::transform(jsonBeacons.begin(), jsonBeacons.end(), jsonBeacons.begin(), ::toupper);

    rapidjson::Document d;
    d.Parse(jsonBeacons.c_str());

    int i = 0;

    int cnt = d.MemberCount();

    int indices[cnt];

    for (i = 0; i < cnt; i++) {
        indices[i] = i;
    }

    int a, b, swap;
    for (b = 0; b < cnt - 1; b++) {
        for (a = 0; a < cnt - 1 - b; a++) {
            if(d[indices[a]]["RSSI"] . GetInt() > d[indices[a + 1]]["RSSI"] . GetInt()) {
                swap = indices[a];
                indices[a] = indices[a + 1];
                indices[a + 1] = swap;
            }
        }
    }

    String key;
    std::vector<String> posIds(ULL cnt);

    int count = 0;

    /*
     * UMM -> PosId
     */
    for (i = 0; i < cnt; i++) {
        key = d[indices[i]]["PROXIMITYUUID"].GetString();
        key += ":";
        key += d[indices[i]]["MAJOR"].GetString();
        key += ":";
        key += d[indices[i]]["MINOR"].GetString();

        reply = RedisCommand(key.c_str(), "GET %s", key.c_str());

        if (reply->type == REDIS_REPLY_STRING) {
            posIds[count++] = reply->str;
        }
    }

    std::vector<String> planIds(ULL count);

    for (i = 0; i < count; ++i) {
        key = "POSID:PLANID:";
        key += posIds[i];

        reply = RedisCommand(key.c_str(), "ZRANGE %s %d %d %s", key.c_str(), 0, -1, "WITHSCORES");

        if (reply->type == REDIS_REPLY_ARRAY) {
            for (int j = 0; j < (int) reply->elements / 2; j++) {
                planIds.push_back(reply->element[j * 2]->str);
            }
        }
    }

    String ret = "[";

    for (i = 0; i < (int) planIds.size(); i++) {
        key = "ADPLAN:ADC:";
        key += planIds[i];

        reply = RedisCommand(key.c_str(), "GET %s", key.c_str());

        if (reply->type == REDIS_REPLY_STRING) {
            ret += reply->str;
            ret += ",";
        }
    }

    ret[ret.size() - 1] = ']';

    return ret;
}
